package dao.Impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import bean.Student;
import dao.StudentDao;
import util.DatabaseBean;

public class StudentDaoImpl implements StudentDao{
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;

	@Override
	public List<Student> findAll() {

		List<Student> students = new ArrayList<Student>();
		try {
			conn=DatabaseBean.getConnection();

			String sql = "select stuno,stuname,stusex from t_student";
			pstmt = conn.prepareStatement(sql);

			rs = pstmt.executeQuery();
			while (rs.next()) {
				Student stu = new Student();
				stu.setStuno(rs.getString("stuno"));
				stu.setStuname(rs.getString("stuname"));
				stu.setStusex(rs.getString("stusex"));
				students.add(stu);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DatabaseBean.close(rs, pstmt, conn);
		}
		return students;
	}

	@Override //
	public List<Student> selectStudentByStuname(String stuname) {

		List<Student> students = new ArrayList<Student>();
		try {
			conn=DatabaseBean.getConnection();
			String sql = "select stuno,stuname,stusex from t_student where stuname like ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "%" + stuname + "%");

			rs = pstmt.executeQuery();
			while (rs.next()) {
				Student stu = new Student();
				stu.setStuno(rs.getString("stuno"));
				stu.setStuname(rs.getString("stuname"));
				stu.setStusex(rs.getString("stusex"));
				students.add(stu);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DatabaseBean.close(rs, pstmt, conn);
		}
		return students;
	}


	@Override //
	public boolean deleteStudent(String stuno) {
		try {   
			conn=DatabaseBean.getConnection();
			String sql = "delete from t_student where stuno=?";
			pstmt = conn.prepareStatement(sql);

			pstmt.setString(1,stuno);

			int result = pstmt.executeUpdate();
			//pstmt.close(); 
			//conn.close();
			if(result>0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DatabaseBean.close(rs, pstmt, conn);
		}
		return false;
	}




	@Override
	public boolean  saveStudent(Student stu) {
		try {

			conn=DatabaseBean.getConnection();
			//String sql = "insert into t_student(stuno,stuname,stusex) values(?,?,?)";
			String sql = "update t_student set stuname=?,stusex=? where stuno=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, stu.getStuname());
			pstmt.setString(2, stu.getStusex());
			pstmt.setString(3, stu.getStuno());

			int result = pstmt.executeUpdate();
			//pstmt.close(); 
			//conn.close();
			if(result>0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DatabaseBean.close(rs, pstmt, conn);
		}

		return false;
	}
}
